package cz.edukomplex.kosilka.client.content.block;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;

import com.fredhat.gwt.xmlrpc.client.XmlRpcClient;
import com.fredhat.gwt.xmlrpc.client.XmlRpcRequest;
import com.google.gwt.cell.client.ButtonCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.SplitLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;

import cz.edukomplex.kosilka.client.helpers.MyRequestBuilder;
import cz.edukomplex.kosilka.client.helpers.MyXmlRpcClient;
import cz.edukomplex.kosilka.client.model.SubjectModel;

public class BlockContent extends Composite {

	private static BlockContentUiBinder uiBinder = GWT
			.create(BlockContentUiBinder.class);

	interface BlockContentUiBinder extends UiBinder<Widget, BlockContent> {
	}
		
	@UiField SplitLayoutPanel contentContainer;
	@UiField(provided = true) CellList<StudyFieldCellListRow> studyFieldCellList;	
	@UiField(provided = true) CellTable<SubjectModel> subjectCellTable; 
	@UiField HTMLPanel addSubjectPanel;
	@UiField SimplePanel actionPanel;	
	@UiField ScrollPanel cellListScrollPanel;
	@UiField ListBox subjectsListBox;	
	@UiField Button newSubjectButton;	
	@UiField Button addSubjectButton;
	@UiField ScrollPanel scrollPanel;
	
	private ArrayList<StudyFieldCellListRow> studyFieldsArrayList = new ArrayList<StudyFieldCellListRow>();
	private ArrayList<SubjectModel> subjectsCellTableArrayList = new ArrayList<SubjectModel>();
	
		
	public BlockContent() {
		subjectCellTable = new CellTable<SubjectModel>();
		studyFieldCellList = new CellList<StudyFieldCellListRow>(new StudyFieldCell());
		initWidget(uiBinder.createAndBindUi(this));
		initCellList();
		initCellTable();
		initSubjectListBox();		
	}
	
	private void initSubjectListBox() {
		
		
		XmlRpcClient client = MyXmlRpcClient.createClient();
		String methodName = "subject.fetchAll";
		
		XmlRpcRequest<ArrayList<HashMap<String, String>>> subjectRequest = new XmlRpcRequest<ArrayList<HashMap<String,String>>>(
				client, methodName, null, new AsyncCallback<ArrayList<HashMap<String, String>>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(
							ArrayList<HashMap<String, String>> result) {
						
						for (@SuppressWarnings("rawtypes")
						Iterator iterator = result.iterator(); iterator
								.hasNext();) {
							@SuppressWarnings("unchecked")
							HashMap<String, String> hashMap = (HashMap<String, String>) iterator
									.next();
							
							subjectsListBox.addItem(
									hashMap.get("name"),
									hashMap.get("sid")
							);
						}
						
					}
		});
		subjectRequest.execute();		
	}
	
	private void initCellList() {
		
		XmlRpcClient client = MyXmlRpcClient.createClient();
		String methodName = "obor.fetchAll";
		
		XmlRpcRequest<ArrayList<HashMap<String, String>>> oboryRequest = new XmlRpcRequest<ArrayList<HashMap<String,String>>>(
				client, methodName, null, new AsyncCallback<ArrayList<HashMap<String, String>>>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(
							ArrayList<HashMap<String, String>> result) {
						
						for (@SuppressWarnings("rawtypes")
						Iterator iterator = result.iterator(); iterator
								.hasNext();) {
							@SuppressWarnings("unchecked")
							HashMap<String, String> hashMap = (HashMap<String, String>) iterator
									.next();
							
							StudyFieldCellListRow row = new StudyFieldCellListRow(
									hashMap.get("Id_oboru"), 
									hashMap.get("Obor")								
							);
							studyFieldsArrayList.add(row);
						}
						
						studyFieldCellList.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
						final SingleSelectionModel<StudyFieldCellListRow> selectionModel = new SingleSelectionModel<StudyFieldCellListRow>();
						
						/*
						 * Ak uzivatel zvoli v lavom stlpci odbor
						 */
						selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
							
							@Override
							public void onSelectionChange(SelectionChangeEvent event) {
								addSubjectPanel.setVisible(true);
								scrollPanel.setVisible(true);
								String id = selectionModel.getSelectedObject().idStudyField;
								
								/*
								 * Posle poziadavku na Subject serivice
								 */
								XmlRpcClient client = MyXmlRpcClient.createClient();
								String methodName = "subject.fetchSubjectsByIdOboru";
								Object[] params = new Object[]{id};
								
								XmlRpcRequest<ArrayList<HashMap<String, String>>> subjectsRequest = new XmlRpcRequest<ArrayList<HashMap<String,String>>>(
										client, methodName, params, new AsyncCallback<ArrayList<HashMap<String, String>>>() {

											@Override
											public void onFailure(
													Throwable caught) {
												// TODO Auto-generated method stub
												
											}

											@Override
											public void onSuccess(
													ArrayList<HashMap<String, String>> result) {
												subjectsCellTableArrayList.clear();
												
												for (@SuppressWarnings("rawtypes")
												Iterator iterator = result
														.iterator(); iterator
														.hasNext();) {
													@SuppressWarnings("unchecked")
													HashMap<String, String> hashMap = (HashMap<String, String>) iterator
															.next();
																									
													SubjectModel row = new SubjectModel(
															hashMap.get("sid"), 
															hashMap.get("name"),
															hashMap.get("short")
													);
													subjectsCellTableArrayList.add(row );
													
												}
												
												refreshCellTable();
											}
										
								});
								
								subjectsRequest.execute();
							}
						});
						
						
						studyFieldCellList.setSelectionModel(selectionModel);
						refreshCellList();
					}
		});
		
		oboryRequest.execute();
	}

	private void initCellTable() {
		subjectCellTable.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.ENABLED);
		SingleSelectionModel<SubjectModel> selectionModel = new SingleSelectionModel<SubjectModel>();
		subjectCellTable.setSelectionModel(selectionModel);
		
		Column<SubjectModel, String> subjectName = new Column<SubjectModel, String>(new ClickableTextCell()) {
			
			@Override
			public String getValue(SubjectModel object) {
				return object.name;
			}
		};
		
		subjectName.setFieldUpdater(new FieldUpdater<SubjectModel, String>() {
			
			@Override
			public void update(int index, SubjectModel object, String value) {
				Window.alert("Click na tabulku, ktory zobrazi otazky");			
			}
		});
		
		Column<SubjectModel, String> deleteButton = new Column<SubjectModel, String>(new ButtonCell()) {
			
			@Override
			public String getValue(SubjectModel object) {
				return "X";
			}
		};
		deleteButton.setFieldUpdater(new FieldUpdater<SubjectModel, String>() {
			
			@Override
			public void update(int index, SubjectModel object, String value) {
				deleteSubjectFromCellTable(object,index);
				
			}
		});
		
		subjectCellTable.addColumn(subjectName,"Predmet");
		subjectCellTable.addColumn(deleteButton);
		refreshCellTable();
		
	}

	private void deleteSubjectFromCellTable(final SubjectModel subject, final int arrayListIndex) {
		
		@SuppressWarnings("unchecked")
		SingleSelectionModel<StudyFieldCellListRow> selectionModel = (SingleSelectionModel<StudyFieldCellListRow>)studyFieldCellList.getSelectionModel();		
		
		XmlRpcClient client = MyXmlRpcClient.createClient();
		String methodName = "subject.deleteSubjectFromObor";
		Object[] params = new Object[]{subject.sid,selectionModel.getSelectedObject().idStudyField};
		
		XmlRpcRequest<Boolean> subjectReqeuest = new XmlRpcRequest<Boolean>(
				client, methodName, params, new AsyncCallback<Boolean>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(Boolean result) {
						/*
						 * Ak sa podarilo odstranit
						 */
						if(result){
							subjectsCellTableArrayList.remove(arrayListIndex);
							refreshCellTable();
						}
						else {
							Window.alert("Predmet sa nepodarilo odstrániť");
						}
					}
		});
		subjectReqeuest.execute();
	}

	private void addSubjectToCellTable() {

		final String sid = subjectsListBox.getValue(subjectsListBox.getSelectedIndex());
		final String subjectName = subjectsListBox.getItemText(subjectsListBox.getSelectedIndex());
		@SuppressWarnings("unchecked")
		SingleSelectionModel<StudyFieldCellListRow> selectionModel = 
			(SingleSelectionModel<StudyFieldCellListRow>)studyFieldCellList.getSelectionModel();
		
		String idStudyField = selectionModel.getSelectedObject().idStudyField;
				 
		XmlRpcClient client = MyXmlRpcClient.createClient();
		String methodName = "subject_st_obory.add";
		Object[] params = new Object[]{sid,idStudyField};
		
		XmlRpcRequest<Boolean> request = new XmlRpcRequest<Boolean>(
				client, methodName, params,	new AsyncCallback<Boolean>() {

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}

					@Override
					public void onSuccess(Boolean result) {
						if(result){
							SubjectModel row = new SubjectModel(sid, subjectName,null);
							subjectsCellTableArrayList.add(row);
							Collections.sort(subjectsCellTableArrayList);
							refreshCellTable();
						}
						else {
							Window.alert("Predmet sa nepodarilo pridať");	
						}
						
					}
		});
		request.execute();		
	}
	
	@UiHandler("addSubjectButton")
	public void handleAddSubjectButtonClick(ClickEvent e){
		addSubjectToCellTable();		
	}	

	private void refreshCellList() {
		studyFieldCellList.setPageSize(studyFieldsArrayList.size());
		studyFieldCellList.setRowCount(studyFieldsArrayList.size(),true);
		studyFieldCellList.setRowData(0, studyFieldsArrayList);

		//Nastavenie vysky laveho panelu		
		int windowHeight = Window.getClientHeight();		
		int contentPosition = contentContainer.getAbsoluteTop();
		String height = (windowHeight - contentPosition) + "px";
		contentContainer.setHeight(height);
	}
	
	private void refreshCellTable() {
		//nastavenie velkosti tabulky na velkost zaznamov
		subjectCellTable.setPageSize(subjectsCellTableArrayList.size());
		//Nastavnie poctu riadkov
		subjectCellTable.setRowCount(subjectsCellTableArrayList.size(), true);
	    // Obnovenie tabulky s novymi datami
		subjectCellTable.setRowData(0, subjectsCellTableArrayList);					
	}	
}